package com.xiaoxin.interceptor;

import com.xiaoxin.commons.utils.JwtUtils;
import com.xiaoxin.model.domain.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xiaoxiaode
 * @date 2021-08-29-22:54
 **/
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头
        String token = request.getHeader("Authorization");
        //使用工具类,判断token是否有效
       /* boolean verifyToken = JwtUtils.verifyToken(token);
        //如果token失败,返回401
        if (!verifyToken) {
            response.setStatus(401);
            return false;
        }*/
        //正常则放行
        //解析token,获取id和手机号码,构造user对象,存入threadlocal
        Claims claims = JwtUtils.getClaims(token);
        String mobile = (String) claims.get("mobile");
        Integer id = (Integer) claims.get("id");
        User user = new User();
        user.setId(Long.valueOf(id));
        user.setMobile(mobile);
        UserHolder.set(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
